//
//  MetaViewController.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "MetaViewController.h"

#import "MetaNameController.h"
#import "MetaInfoController.h"
#import "MetaVersionController.h"
#import "MetaPublicController.h"
#import "MetaTagController.h"
#import "MetaPermissionController.h"

#import "FormattingUtilities.h"

#import "GSSCommunicator.h"
#import "GSSOperation.h"
#import "GSSObject.h"

@implementation MetaViewController

@synthesize normalFooterView;
@synthesize editingFooterView;
@synthesize trashFooterView;

@synthesize emailLinkButton;
@synthesize moveToTrashButton;
@synthesize restoreFromTrashButton;
@synthesize deletePermanentlyButton;

//MARK: -

- (id)initWithGSSObject:(GSSObject *)anObject {
    if (self = [super initWithNibName:@"MetaViewController" bundle:nil]) {
        object = [anObject retain];
        controllers = [[NSMutableArray alloc] init];
        
        [controllers removeAllObjects];
        
        [controllers addObject:[[[MetaNameController alloc] initWithObject:object] autorelease]];
        [controllers addObject:[[[MetaInfoController alloc] initWithObject:object] autorelease]];
        
        if (object.type == GSSObjectTypeFile) {
            [controllers addObject:[[[MetaVersionController alloc] initWithObject:object] autorelease]];
            [controllers addObject:[[[MetaPublicController alloc] initWithObject:object] autorelease]];
            [controllers addObject:[[[MetaTagController alloc] initWithObject:object] autorelease]];
        }
        
        [controllers addObject:[[[MetaPermissionController alloc] initWithObject:object] autorelease]];
    }
        
    return self;
}

- (void)dealloc {
    [object release];
    [controllers release];
    
    [normalFooterView release];
    [editingFooterView release];
    
    [super dealloc];
}

//MARK: -

- (void)reloadData {
    self.title = object.name;

    if (object.deleted)
        self.tableView.tableFooterView = self.trashFooterView;
    else
        self.tableView.tableFooterView = self.isEditing ? self.editingFooterView : self.normalFooterView;
    
    [self.tableView reloadData];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)anObject change:(NSDictionary *)change context:(void *)context {
    [self reloadData];
}

//MARK: -
//MARK: UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!object.deleted)
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    [self.emailLinkButton setTitle:LocalizedString(@"Email link")
                          forState:UIControlStateNormal];
    [self.moveToTrashButton setTitle:LocalizedString(@"Move to trash")
                            forState:UIControlStateNormal];
    [self.restoreFromTrashButton setTitle:LocalizedString(@"Restore from trash")
                                 forState:UIControlStateNormal];
    [self.deletePermanentlyButton setTitle:LocalizedString(@"Delete permanently")
                                  forState:UIControlStateNormal];
    
    for (SectionController *controller in controllers) {
        controller.tableView = self.tableView;
        controller.navigationController = self.navigationController;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setToolbarHidden:YES animated:NO];

    [object addObserver:self forKeyPath:@"meta" options:0 context:NULL];
    [object addObserver:self forKeyPath:@"error" options:0 context:NULL];    
        
    if (object.isStale || object.isPartial)
        [[GSSCommunicator defaultCommunicator] updateMetaOfObject:object];
    
    [self reloadData];
    
    [object updateMetaAccessDate];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [object removeObserver:self forKeyPath:@"meta"];
    [object removeObserver:self forKeyPath:@"error"];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return YES;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
        
    for (SectionController *controller in controllers)
        controller.editing = editing;
    
    [self reloadData];
}

//MARK: -
//MARK: UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [controllers count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[controllers objectAtIndex:section] numberOfRows];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [[controllers objectAtIndex:indexPath.section] cellForRow:indexPath.row];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[controllers objectAtIndex:section] titleForHeader];
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return [[controllers objectAtIndex:section] titleForFooter];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    return [[controllers objectAtIndex:indexPath.section] commitEditingStyle:editingStyle
                                                                      forRow:indexPath.row];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


//MARK: -
//MARK: UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[controllers objectAtIndex:indexPath.section] didSelectRow:indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [[controllers objectAtIndex:indexPath.section] heightForRow:indexPath.row];
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [[controllers objectAtIndex:indexPath.section] editingStyleForRow:indexPath.row];
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return [[controllers objectAtIndex:indexPath.section] shouldIndentWhileEditingRow:indexPath.row];
}


//MARK: -
//MARK: MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
	if (result == MFMailComposeResultFailed) {
        NSString *message = [NSString stringWithFormat:
                             LocalizedString(@"{Email operation failed}"),
                             [error userInfo]];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:LocalizedString(@"Email link")
                                                        message:message
                                                       delegate:nil
											  cancelButtonTitle:nil
											  otherButtonTitles:LocalizedString(@"OK"), nil];
		[alert show];
		[alert release];
	}
	[self dismissModalViewControllerAnimated:YES];
}


//MARK: -
//MARK: IBActions

- (IBAction)emailLink {
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:LocalizedString(@"{Email subject}")];
		
	NSString *emailBody = [NSString stringWithFormat:LocalizedString(@"{Email body}"), object.uri];
	[picker setMessageBody:emailBody isHTML:YES];
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

- (IBAction)moveToTrash {
    [[GSSCommunicator defaultCommunicator] moveToTrashObject:object];
    object.deleted = YES;
    [object save];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)restoreFromTrash {
    [[GSSCommunicator defaultCommunicator] restoreFromTrashObject:object];
    object.deleted = NO;
    [object save];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)deletePermanently {
    [[GSSCommunicator defaultCommunicator] deleteObject:object];
    [object delete];
    [self.navigationController popViewControllerAnimated:YES];    
}

@end